package com.qf.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.pojo.Admin;
import com.qf.pojo.JSONResult;
import com.qf.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @RequestMapping("login")
    public String login(Admin admin, HttpSession session) {
        boolean login = adminService.login(admin);
        if (login){
            session.setAttribute("admin",admin.getUsername());
            return "success";
        } else {
            return "fail";
        }
    }

    @RequestMapping("list")
    public JSONResult findList(
            @RequestParam(value = "page",required = false,defaultValue = "1") Integer pageNum,
            @RequestParam(value = "limit",required = false,defaultValue = "5") Integer pageSize) {
        JSONResult jsonResult = new JSONResult();
        PageHelper.startPage(pageNum,pageSize);
        List<Admin> admins = adminService.findAll();
        PageInfo<Admin> pageInfo = new PageInfo<>(admins);
        jsonResult.setCode(0);
        jsonResult.setCount(pageInfo.getTotal());
        jsonResult.setMsg("success");
        jsonResult.setData(admins);

        return jsonResult;
    }

    @RequestMapping("add")
    public JSONResult addAdmin(Admin admin) {
        adminService.addAdmin(admin);
        JSONResult jsonResult = new JSONResult();
        jsonResult.setCode(10000);
        return jsonResult;
    }

    @RequestMapping("remove")
    public String remove(Integer id) {
        adminService.remove(id);
        return "success";
    }

    @RequestMapping("removeAll")
    public String removeAll(Integer[] ids) {
        adminService.removeAll(Arrays.asList(ids));
        return "success";
    }

    @RequestMapping("updateAdmin")
    public JSONResult updateAdmin(Admin admin) {
        adminService.updateAdmin(admin);
        JSONResult jsonResult = new JSONResult();
        jsonResult.setCode(10000);
        return jsonResult;
    }

}
